const { parentPort } = require('worker_threads');
const fs = require('fs');
const path = require('path');
const fetch = require('node-fetch');
const FormData = require('form-data');

class CameraDriver {
  constructor(photoPath, photoUrl) {
    this.photoPath = photoPath;
    this.photoUrl = photoUrl;
  }

  // 处理plateno模式：重命名图片文件
  async handlePlatenoMode(plateno) {
    try {
      const newPath = path.join(path.dirname(this.photoPath), `${plateno}.jpg`);
      
      // 如果目标文件已存在，先删除
      if (fs.existsSync(newPath)) {
        fs.unlinkSync(newPath);
      }
      
      // 重命名图片文件
      fs.renameSync(this.photoPath, newPath);
      
      return { success: true };
    } catch (error) {
      return { success: false, error: error.message };
    }
  }

  // 处理lpc模式：上传图片
  async handleLpcMode(plateno, lpc) {
    try {
      const platenoPath = path.join(path.dirname(this.photoPath), `${plateno}.jpg`);

      if (!fs.existsSync(platenoPath)) {
        throw new Error(`未找到文件: ${plateno}.jpg`);
      }

      // 读取图片文件
      const imageBuffer = fs.readFileSync(platenoPath);

      // 创建FormData对象
      const formData = new FormData();
      formData.append('file', imageBuffer, {
        filename: `${lpc}.jpg`,
        contentType: 'image/jpeg'
      });

      // 上传图片
      const response = await fetch(this.photoUrl, {
        method: 'POST',
        body: formData,
        headers: formData.getHeaders()
      });

      if (!response.ok) {
        throw new Error(`上传失败: ${response.statusText}`);
      }

      const result = await response.json();

      return { success: true, data: result };
    } catch (error) {
      return { success: false, error: error.message };
    }
  }
}

// 创建相机驱动实例
let cameraDriver = null;

// 处理来自主线程的消息
parentPort.on('message', async (data) => {
  // 初始化驱动
  if (data.type === 'init') {
    cameraDriver = new CameraDriver(data.photoPath, data.photoUrl);
    parentPort.postMessage({ success: true, type: 'init' });
    return;
  }

  // 确保驱动已初始化
  if (!cameraDriver) {
    parentPort.postMessage({
      success: false,
      error: '相机驱动未初始化'
    });
    return;
  }

  // 处理不同的操作模式
  let result;
  if (data.type === 'plateno') {
    result = await cameraDriver.handlePlatenoMode(data.plateno);
  } else if (data.type === 'lpc') {
    result = await cameraDriver.handleLpcMode(data.plateno, data.lpc);
  } else {
    result = {
      success: false,
      error: '未知的操作类型'
    };
  }

  parentPort.postMessage(result);
});